#include "SmartHomeMonitorServer.h"
#include "MyLogger.h"
#include "UserService.h"
#include "Message.h"
#include <iostream>
using namespace std;
namespace SOS{
SmartHomeMonitorServer::SmartHomeMonitorServer(int threadNum, int taskSize, unsigned short port, const string & ip)
:_threadpool(threadNum,taskSize)
,_tcpServer(port,ip)
{
    using namespace std::placeholders;
    _tcpServer.setAllCallbacks(std::bind(&SmartHomeMonitorServer::onConnection,this,_1)
                               ,std::bind(&SmartHomeMonitorServer::onMessage,this,_1)
                                ,std::bind(&SmartHomeMonitorServer::onClose,this,_1));
}

SmartHomeMonitorServer::~SmartHomeMonitorServer(){

}

void SmartHomeMonitorServer::start(){
    _threadpool.start();
    _tcpServer.start();
}

void SmartHomeMonitorServer::stop(){
    _tcpServer.stop();
    _threadpool.stop();
}

void SmartHomeMonitorServer::onConnection(TcpConnectionPtr conn){
    LogInfo("tcp %s has connected.\n", conn->toString().c_str());
}

void SmartHomeMonitorServer::onMessage(TcpConnectionPtr conn){
    cout<<"onMesaage..."<<endl;
    Packet packet;
    int ret=conn->readPacket(packet);
    cout<<"read : "<<ret<<"bytes\n"<<endl
        <<"packet.length"<<packet.length<<endl
        <<"packet,date"<<packet.msg<<endl;
    switch(packet.type){
        case TASK_LOGIN_SECTION1:{
            UserLoginSection1 userlogin1(conn,packet);
            _threadpool.addTask(std::bind(&UserLoginSection1::process,userlogin1));
        }
        break;
        case TASK_LOGIN_SECTION2:{}
        break;
    }
}

void SmartHomeMonitorServer::onClose(TcpConnectionPtr conn){
    LogInfo("tcp %s has closed.\n",conn->toString().c_str());
}
}//endof namespace